package networks.manager;

import java.util.HashMap;
import networks.event.Delegate;
import networks.protocol.Message;

public class BroadcastFactory {
    private static final BroadcastFactory _instance = new BroadcastFactory();

    private BroadcastFactory() {
        _callbacks = new HashMap<String, Delegate.ActionOne<Message>>();
    }

    public synchronized static BroadcastFactory Instance() {
        return _instance;
    }

    public void Dispose() {
        _callbacks.clear();
    }

    private HashMap<String, Delegate.ActionOne<Message>> _callbacks;

    public HashMap<String, Delegate.ActionOne<Message>> getCallbacks() {
        return _callbacks;
    }

    public void RegistEvents() {
        // lobby
        _callbacks.put(Routes.S2C_LOBBY_ON_CHAT, new Delegate.ActionOne<Message>() {
            @Override
            public void Invoke(Message msg) {
                GameHandler.onPushUserChat(msg);
            }
        });
        _callbacks.put(Routes.S2C_LOBBY_ON_ENTER, new Delegate.ActionOne<Message>() {
            @Override
            public void Invoke(Message msg) {
                GameHandler.onPushUserEnter(msg);
            }
        });
        _callbacks.put(Routes.S2C_LOBBY_ON_LEAVE, new Delegate.ActionOne<Message>() {
            @Override
            public void Invoke(Message msg) {
                GameHandler.onPushUserLeave(msg);
            }
        });
        // room
        _callbacks.put(Routes.S2C_ROOM_ON_PLAYER_INFO, new Delegate.ActionOne<Message>() {
            @Override
            public void Invoke(Message msg) {
                GameHandler.onPushPlayerInfo(msg);
            }
        });
        _callbacks.put(Routes.S2C_ROOM_ON_PLAYER_LEAVE, new Delegate.ActionOne<Message>() {
            @Override
            public void Invoke(Message msg) {
                GameHandler.onPushPlayerLeave(msg);
            }
        });
        _callbacks.put(Routes.S2C_ROOM_ON_MATCH, new Delegate.ActionOne<Message>() {
            @Override
            public void Invoke(Message msg) {
                GameHandler.onPushRoomMatch(msg);
            }
        });
    }

    public void InvokeHandle(String route, Message data) {
        Delegate.ActionOne<Message> handler = _callbacks.get(route);
        if (handler != null) {
            handler.Invoke(data);
        } else {
            System.out.println("cannot find handler for " + route);
        }
    }
}
